﻿using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;

namespace Coding4Fun.UsbCannon.Phone
{
	[DataContract]
	public class AppSettings
	{
		private const string SettingsFileName = "Settings.dat";

		[DataMember]
		public string EndpointUrl { get; set; }

		public static AppSettings Load()
		{
			AppSettings settings = null;

			using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
			{
				using (var stream = new IsolatedStorageFileStream(SettingsFileName, FileMode.OpenOrCreate, isf))
				{
					if (stream.Length > 0)
					{
						var dcs = new DataContractSerializer(typeof(AppSettings));
						settings = dcs.ReadObject(stream) as AppSettings;
					}
				}
			}

			return settings ??
				   (new AppSettings
				   {
					   EndpointUrl = "crutkasdesktop",
				   });
		}

		public void Save()
		{
			using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
			{
				using (var stream = new IsolatedStorageFileStream(SettingsFileName, FileMode.Create, isf))
				{
					var dcs = new DataContractSerializer(typeof(AppSettings));
					dcs.WriteObject(stream, this);
				}
			}
		}
	}
}
